package com.arpa.wms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.dto.WarehouseSpaceDTO;
import com.arpa.wms.domain.entity.WarehouseSpace;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.WarehouseSpaceVO;
import com.arpa.wms.domain.vo.WarehouseVO;
import com.arpa.wms.service.IWarehouseService;
import com.arpa.wms.service.IWarehouseSpaceService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 库区 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Api(tags = "库区")
@RestController
@RequestMapping(value = "/warehouseSpace", produces = "application/json;charset=UTF-8")
@Log4j2
public class WarehouseSpaceController {

    private final IWarehouseSpaceService iWarehouseSpaceService;

    public WarehouseSpaceController(IWarehouseSpaceService iWarehouseSpaceService) {
        this.iWarehouseSpaceService = iWarehouseSpaceService;
    }


    /**
     * 获取 库区 列表
     *
     * @param warehouseSpaceDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 库区 列表", notes = "获取 库区 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseSpaceVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(WarehouseSpaceDTO warehouseSpaceDTO, HttpServletRequest request) {
        try {

            //登录账号授权的仓库过滤
            warehouseSpaceDTO.setWarehouseCodes(UserUtil.getAuthorizeWarehouseCodes());
            warehouseSpaceDTO.setGroupCode(UserUtil.getBranchCode());
            WarehouseSpaceVO warehouseSpaceVOSum = iWarehouseSpaceService.queryListSum(warehouseSpaceDTO);
            List<WarehouseSpaceVO> warehouseSpaceVOList = iWarehouseSpaceService.queryList(warehouseSpaceDTO);

            Page returnPage = new Page(warehouseSpaceDTO.getPageNum(), warehouseSpaceDTO.getPageSize());
            returnPage.setRecords(warehouseSpaceVOList);
            returnPage.setTotal(warehouseSpaceVOSum.getTotal());
            returnPage.setSumObject(warehouseSpaceVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 库区
     *
     * @param entity  WarehouseSpace
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 库区 ", notes = "添加 库区 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(WarehouseSpace.Save.class)WarehouseSpace entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            entity.setStatus(StatusEnum.UNACTIVE.getValue());
            Result validResult = iWarehouseSpaceService.validateSpace(entity);
            if (!validResult.isOk()) {
                return validResult;
            }
            iWarehouseSpaceService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取库区详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取库区详情", notes = "获取库区详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "code", value = "库区code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseSpaceVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result warehouseSpace(@PathVariable String code, HttpServletRequest request) {
        try {
            WarehouseSpaceVO entity = iWarehouseSpaceService.getWarehouseSpace(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改库区
     *
     * @param entity  库区
     * @param request
     * @return
     */
    @ApiOperation(value = "修改库区", notes = "修改库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(WarehouseSpace.Update.class)WarehouseSpace entity, HttpServletRequest request) {
        if (StrUtil.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        // 校验库区信息
        Result validResult = iWarehouseSpaceService.validateSpace(entity);
        if (!validResult.isOk()) {
            return validResult;
        }

        int updateNum = iWarehouseSpaceService.updateByCode(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("修改成功,更新" + updateNum + "条数据！");
        }
    }

    /**
     * 删除 库区
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 库区 ", notes = "删除 库区 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "库区code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            return iWarehouseSpaceService.deleteByCode(codes);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 启用仓库
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "启用库区", notes = "启用库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        int updateNum = iWarehouseSpaceService.activeStatus(codes);
        int failNum = codes.size() - updateNum;
        return Result.ok("启用成功" + updateNum + "条；失败" + failNum + "条；");
    }

    /**
     * 停用库区
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "停用库区", notes = "停用库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iWarehouseSpaceService.unactiveStatus(codes);
        Integer success = MapUtil.getInt(result,"success");
        List<String> spaceNames = MapUtil.get(result, "spaceNames", List.class);
        int failNum = codes.size() - success;
        StringBuilder info = new StringBuilder();
        info.append("停用成功" + success + "条；失败" + failNum + "条；");
        if(IterUtil.isNotEmpty(spaceNames)){
            for(String m: spaceNames){
                info.append("<br><font color='red'>库区【"+m+"】停用失败，库存不为0;</font>");
            }
        }
        return Result.ok(info.toString());
    }


    /**
     * 获取 库区下拉列表数据
     *
     * @param warehouseCode
     * @param request
     * @return
     */
    @ApiOperation(value = "获取库区下拉列表数据", notes = "获取库区下拉列表数据,不包含临时库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "warehouseCode", value = "仓库code", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseData")
    public Result chooseData(@RequestParam(defaultValue = "") String warehouseCode, HttpServletRequest request) {
        try {
            List<WarehouseSpaceVO> warehouseSpaceVOList = iWarehouseSpaceService.findWarehouseSpace(warehouseCode);
            return Result.ok().data(warehouseSpaceVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 所有库区下拉列表数据（包含临时库区数据）
     *
     * @param warehouseCode
     * @param request
     * @return
     */
    @ApiOperation(value = "获取库区下拉列表数据", notes = "获取 库区下拉列表数据,包含临时库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "warehouseCode", value = "仓库code", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseAllData")
    public Result chooseAllData(@RequestParam(defaultValue = "") String warehouseCode, HttpServletRequest request) {
        try {
            List<WarehouseSpaceVO> warehouseSpaceVOList = iWarehouseSpaceService.findAllWarehouseSpace(warehouseCode);
            return Result.ok().data(warehouseSpaceVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

}
